package smartcase.config.log;

import lombok.Data;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import smartcase.config.ConfigurationDefineImpl;

import java.io.IOException;

import static smartcase.base.ApplicationContextProviderKt.getBean;

@Data
public class CLSClient {

  public PostStructLogRequest newPostStructLogRequest(CLS.LogGroupList logGroupList) {
    ElkAccessConfiguration cfg = getBean(ElkAccessConfiguration.class);
    return new PostStructLogRequest(
        cfg.getEndpoint(),
        cfg.getRegion(),
        cfg.getSecretId(),
        cfg.getSecretKey(),
        cfg.getTopicId(),
        logGroupList);
  }

  public String send(PostStructLogRequest req) throws IOException {
    String result = null;
    switch (req.getMethod()) {
      case "POST":
        {
          HttpPost post = new HttpPost(req.getUrl());
          req.getHeaders().forEach(post::addHeader);
          post.setEntity(req.getHttpEntity());
          try (CloseableHttpClient httpClient = HttpClients.createDefault();
              CloseableHttpResponse response = httpClient.execute(post)) {
            result = EntityUtils.toString(response.getEntity());
          }
          break;
        }
      case "GET":
        {
          break;
        }
      default:
        throw new IllegalStateException("Unexpected value: " + req.getMethod());
    }
    return result;
  }


}
